package cn.xspace.library.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.NavTagBean;
import com.xspace.android.xafcommon.been.QueryInitialDataBean;
import com.xspace.android.xafcommon.location.MyAMapLocation;
import com.xspace.android.xafcommon.network.exception.HttpException;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.ClassUtil;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.ModuleConfig;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.util.WorkLogConstant;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.library.R;
import cn.xspace.library.ui.activity.InfoEditActivity;
import cn.xspace.library.ui.activity.LoginAct;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/12/5.
 */

public class BldNavigation {

    private static final String TAG = BldNavigation.class.getSimpleName();

    public final static String KEY_BUNDLER = "bundle";
    public final static String EXTRA_CONVERSION = "extra_convesition";
    public final static String SENDER_ID = "d";
    public final static String SENDER_NAME = "senderName";
    public final static String CHAT_TYPE = "chatType";
    public final static String CHAT_NAME = "chatName";
    public final static String CHAT_SENDER_LOGO = "senderLogo";
    public final static String CHAT_SENDER_SEX = "senderSex";
    public final static String GROUP_TYPE = "group_type";//0 普通群组 2 专业群组 3机构群组
    public final static String LATITUDE = "latitude";
    public final static String LONGITUDE = "longitude";
    public final static String ADDRESS = "address";
    public final static String SNAP_PATH = "snapPath";
    public final static String SEARCH_TYPE = "searchType";
    public final static String SEARCH_GROUP_MEMBER = "search_group_member";
    public final static String SEARCH_MY_FRIEND = "search_my_friend";
    // 跳转到机构微农信列表时判断是否是查看历史消息使用的字段
    public final static String LOOK_HISTORY = "look_history";
    //是否被踢出了群组
    public final static String IS_QUIT = "isquit";
    public static String ACTION_REFRESH_INDEX = "indexRefreshing";
    public static String ACTION_REFRESH_INFO = "userInfoRefresh";
    public static String ACTION_REFRESH_LOGO = "userLogoRefresh";

    public static String ForwardTitle = "mTitle";
    public static String ForwardUrl = "mUrl";

    public static String FormId = "formId";
    public static String FormUrl = "formUrl";
    public static String FormType = "formType";
    public static String FormName = "formName";
    public static String FormCanTAlk = "formCanTalk";

    public interface ILogInListener {

        void onLogInError(Context mContext, Throwable e);

        void onLogInSuccess(Context mContext, QueryInitialDataBean result);
    }


    public static void HxXmppLogin(Context mContext) {
        Class wnxClz = ClassUtil.getClassByName(ClassUtil.WNX_SERVICE);
        if (wnxClz == null) {
            return;
        }
        //这里进行Xmpp登录和环信登录
        Intent mIntent = new Intent(mContext, wnxClz);
        String xmppLogin = ClassUtil.getClassField(ClassUtil.WNX_SERVICE, "XMPP_LOGIN").toString();
        String hxLogin = ClassUtil.getClassField(ClassUtil.WNX_SERVICE, "HX_LOGIN").toString();
        mIntent.putExtra(ModuleConfig.OPERATION, xmppLogin);
        mContext.startService(mIntent);
        Intent hxIntent = new Intent(mContext, wnxClz);
        hxIntent.putExtra(ModuleConfig.OPERATION, hxLogin);
        mContext.startService(hxIntent);
    }


    public static void wnxMsgForward(Context mContext, String url, String title) {
        Class wnxClz = null;
        try {
            wnxClz = Class.forName(ClassUtil.WNX_SERVICE);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (wnxClz == null) {
            T.showSingleL("没有微农信模块");
        } else {
            String forward = ClassUtil.getClassField(ClassUtil.WNX_SERVICE, "MsgForward").toString();
            Intent intent = new Intent(mContext, wnxClz);// 你想去的activity(exp:Temp)
            intent.putExtra(ModuleConfig.OPERATION, forward);
            intent.putExtra(ForwardUrl, url);
            intent.putExtra(ForwardTitle, title);
            mContext.startService(intent);
        }

    }

    public static void HxXmppLoginout(Context mContext) {
        Class wnxClz = ClassUtil.getClassByName(ClassUtil.WNX_SERVICE);
        if (wnxClz != null) {
            //这里进行Xmpp登录和环信登录
            Intent mIntent = new Intent(mContext, wnxClz);
            String xmppLoginOut = ClassUtil.getClassField(ClassUtil.WNX_SERVICE, "XMPP_LOGIN_OUT").toString();
            mIntent.putExtra(ModuleConfig.OPERATION, xmppLoginOut);
            mContext.startService(mIntent);
        }
    }

    //机构详情页面需要传递参数
    public static void startOrgInfoActivity(Context context, String id) {
        Class clz = ClassUtil.getClassByName(ClassUtil.OrganizationInfoActivity);
        if (clz == null) {
            return;
        }
        if (clz == null) {
            T.showSingleL(context.getResources().getString(R.string.module_wnx_not_have));
            return;
        }
        Intent intent = new Intent(context, clz);
        intent.putExtra(RequestConstant.KEY_ORG_ID, id);
        context.startActivity(intent);
    }

    private static void login(final Context mContext) {
        final Map<String, Object> dataMap = new HashMap<>();
        String user_mobile = MyInfoUtil.getMyMobile(mContext);
        dataMap.put("mobile", user_mobile);
        String password = PreferencesUtils.getPfValue(Constants.ACCOUNT_PASSWORD_KEY);
        dataMap.put("pwd", AppUtils.MD5(password, false));
        //新参数
        dataMap.put("user_mobile", user_mobile);
        dataMap.put("user_pwd", AppUtils.MD5(password, false));
        dataMap.put("app_id", MyInfoUtil.getAppId(mContext));
        commonLogin(mContext, dataMap, new ILogInListener() {
            @Override
            public void onLogInError(Context mContext, Throwable e) {
                if ("010201".equals(e.getMessage())) {
                    T.showSingleL("用户不存在或者密码不正确，请重新登录");
                    Tools.logoutAndClearData(mContext);
                    startLogin(mContext);
                    ((Activity) mContext).finish();
                } else {
                    gotoHomeAct(mContext);
                }
            }

            @Override
            public void onLogInSuccess(Context mContext, QueryInitialDataBean result) {
                loginSuccess(mContext, result, true);
            }
        });
    }

    public static void commonLogin(final Context mContext, final Map<String, Object> dataMap, final ILogInListener
            logInListener) {
        Observable.create(new Observable.OnSubscribe<QueryInitialDataBean>() {
            @Override
            public void call(Subscriber<? super QueryInitialDataBean> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.USER_LOGIN, dataMap);
                if (bean != null) {
                    if (OkHttpUtils.isSuccess(bean)) {
                        QueryInitialDataBean dataBean = JSONUtil.parseJsonToBean(bean.data, QueryInitialDataBean.class);
                        subscriber.onNext(dataBean);
                    } else {
                        subscriber.onError(new HttpException(bean.code));
                    }
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<QueryInitialDataBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                logInListener.onLogInError(mContext, e);
            }

            @Override
            public void onNext(QueryInitialDataBean result) {
                logInListener.onLogInSuccess(mContext, result);
            }
        });
    }

    /**
     * 登录成功,存储用户信息
     * 请求首页
     * 保存信息等
     *
     * @param mContext
     * @param returnRes
     */
    public static void loginSuccess(final Context mContext, final QueryInitialDataBean returnRes, final boolean
            isAuto) {
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                MyInfoUtil.setUserAppInfo(returnRes);

//                //设置导航图标
//                BuildCache.getAppConfigBean(mContext).navigationBean.navTagList.clear();
//                BuildCache.getAppConfigBean(mContext).navigationBean.navTagList.addAll(returnRes.navigateList);
//                BuildCache.setNavigationIcon();
//                //保存导航信息
//                BldNavigation.saveNavigateList(returnRes.navigateList, mContext);
                subscriber.onNext("");
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Object o) {
                        ((BaseActivity) mContext).hideWaitDialog();
                        gotoHomeAct(mContext);
                        //登录成功后就下载主页
//                        OkHttpManager.getInstance().getHtml(mContext, returnRes.appIndex.app_index, "index.html",
//                                new OkHttpManager.IFileDownload() {
//
//                                    @Override
//                                    public void beforeDown() {
//
//                                    }
//
//                                    @Override
//                                    public void downing(float complete) {
//
//                                    }
//
//                                    @Override
//                                    public void downFinish() {
//                                        if (!isAuto) {
//                                            ((BaseActivity) mContext).hideWaitDialog();
//                                        }
//                                        gotoHomeAct(mContext);
//                                    }
//
//                                    @Override
//                                    public void downError() {
//                                        if (!isAuto) {
//                                            ((BaseActivity) mContext).hideWaitDialog();
//                                        }
//                                        gotoHomeAct(mContext);
//                                    }
//                                });
                    }
                });
    }

    /**
     * 跳往登录界面
     *
     * @param mContext
     */
    public static void startLogin(Context mContext) {
        Intent intent = new Intent(mContext, LoginAct.class);
        mContext.startActivity(intent);
    }

    public static void gotoHomeAct(Context mContext) {
        LogUtil.d(TAG, "wubaojie>>>gotoHomeAct: 登录,进入主页");
        Class wnxClass = ClassUtil.getClassByName(ClassUtil.WNX_MAIN_CLASS);
        if (wnxClass != null) {
            mContext.startActivity(new Intent(mContext, wnxClass));
            ((Activity) mContext).finish();
            HxXmppLogin(mContext);
            MyAMapLocation.getInstance().startLocation();//开启定位服务
        }
    }

    public static void saveNavigateList(List<NavTagBean> navigateList, Context mContext) {
        String json = new Gson().toJson(navigateList);
        try {
            FileOutputStream fos = mContext.openFileOutput(Constants.NAVIGATION_JSON, Context.MODE_PRIVATE);
            fos.write(json.getBytes("UTF-8"));
            LogUtil.d(TAG, "wubaojie>>>call: 导航列表保存成功");
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static void login(final Context mContext) {
//        Map<String, Object> dataMap = new HashMap<String, Object>();
//        dataMap.put("mobile", MyInfoUtil.getMyMobile(mContext));
//        String password = (String) PreferencesUtils.getPfValue(mContext, Constants.ACCOUNT_PASSWORD_KEY, String.class
//                .getName());
//        dataMap.put("pwd", AppUtils.MD5(password, false));
//        dataMap.put("app_id", MyInfoUtil.getAppId(mContext));
//        OkHttpManager.getInstance().commonRequestWithoutEncrypt(Constants.URL_QUERY_USERJID, dataMap)
//                .subscribeOn(Schedulers.io())
//                .map(new Func1<BaseReturnBean, QueryInitialDataBean>() {
//                    @Override
//                    public QueryInitialDataBean call(BaseReturnBean baseReturnBean) {
//                        QueryInitialDataBean bean = null;
//                        if ("0".equals(baseReturnBean.code)) {
//                            JSONObject jsn;
//                            try {
//                                Gson mGson = new Gson();
//                                bean = (mGson.fromJson(baseReturnBean.data, new TypeToken<QueryInitialDataBean>() {
//                                }.getType()));
//                                Log.d("QueryInitialDataImpl", "msg:" + baseReturnBean.data);
//                                if (bean.authList != null && bean.authList.size() > 0) {
//                                    //保存 权限json字符串
//                                    String authJSStr = mGson.toJson(bean.authList);
//                                    JSONArray authJSA = new JSONArray(authJSStr);
//                                    JSONObject js = new JSONObject();
//                                    js.put("msgList", authJSA);
//                                    MyInfoUtil.setPostAuthrityData(js.toString());
//                                }
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                        return bean;
//                    }
//                })
//                .doOnNext(new Action1<QueryInitialDataBean>() {
//                    @Override
//                    public void call(QueryInitialDataBean queryInitialDataBean) {
//                        MyInfoUtil.setUserAppInfo(queryInitialDataBean);
//                        BuildCache.getAppConfigBean(mContext).navigationBean.navTagList.clear();
//                        BuildCache.getAppConfigBean(mContext).navigationBean.navTagList.addAll(queryInitialDataBean
//                                .navigateList);
//                        BuildCache.setNavigationIcon();
//                        OkHttpManager.getInstance().getHtml(mContext, queryInitialDataBean.appIndex.app_url, "index" +
//                                ".html", null);
//                        String json = new Gson().toJson(queryInitialDataBean.navigateList);
//                        try {
//                            FileOutputStream fos = mContext.openFileOutput("navigation.json",
//                                    Context.MODE_PRIVATE);
//                            fos.write(json.getBytes("UTF-8"));
//                            L.v("保存成功");
//                            fos.flush();
//                            fos.close();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<QueryInitialDataBean>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        if ("-1".equals(e.getMessage())) {
//                            //password error
//                            T.showSingleL("用户不存在或者密码不正确，请重新登录");
//                            Tools.logoutAndClearData(mContext);
//                            Navigation.startLogin(mContext);
//                            ((FragmentActivity) mContext).finish();
//                        } else {
//                            mContext.startActivity(new Intent(mContext, NavBottomTagActivity.class));
//                            ((FragmentActivity) mContext).finish();
//                            HxXmppLogin(mContext);
//                        }
//                    }
//
//                    @Override
//                    public void onNext(QueryInitialDataBean queryInitialDataBean) {
//                        mContext.startActivity(new Intent(mContext, NavBottomTagActivity.class));
//                        ((FragmentActivity) mContext).finish();
//                        HxXmppLogin(mContext);
//                    }
//                });
//    }


    public static void startNewModuleByKey(String key, Context mContext) {
        try {
            if (BuildConfig.nativeMap.containsKey(key)) {
                BuildConfig.NativeSkip style = BuildConfig.nativeMap.get(key);
                Class clz = ClassUtil.getClassByName(style.getActivityClz());
                if (clz == null) {
                    return;
                }
                Intent mIntent = new Intent(mContext, clz);
//                if (!TextUtils.isEmpty(style.getUrl())) {
//                    //跳转到Url
//                    mIntent.putExtra(Constants.WEBVIEURL, style.getUrl());
//                }
//                mContext.startActivity(mIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void startNewModuleByKey(NavTagBean tagBean, Context mContext) {
        try {
            if (BuildConfig.nativeMap.containsKey(tagBean.navKey)) {
                BuildConfig.NativeSkip style = BuildConfig.nativeMap.get(tagBean.navKey);
                Class clz = ClassUtil.getClassByName(style.getActivityClz());
                if (clz == null) {
                    return;
                }
                Intent mIntent = new Intent(mContext, clz);

                if (BuildConfig.BROWSER_BUILD_URL.equals(tagBean.navKey)) {
                    mIntent.putExtra(Constants.WEBVIEURL, WorkLogConstant.getMyWorkUrl(tagBean.navUrl));
                    mIntent.putExtra(BaseFragment.IS_SHOW_TOP, false);
                    if (TextUtils.isEmpty(tagBean.navTitle)) {
                        mIntent.putExtra(BaseFragment.IS_SHOW_TOP, false);
                    } else {
                        mIntent.putExtra(Constants.TITITL, tagBean.navTitle);
                    }
//                    mUrl = fragmentArgs.getString(Constants.WEBVIEURL);
//                    mTitle = fragmentArgs.getString(Constants.TITITL);
//                    mContent = fragmentArgs.getString(PARAM_CONTENT);
//                    org_id = fragmentArgs.getString(RequestConstant.KEY_ORG_ID);
                } else if (BuildConfig.BROWSER.equals(tagBean.navKey)) {
                    mIntent.putExtra(Constants.WEBVIEURL, tagBean.navUrl);
                    mIntent.putExtra(Constants.TITITL, tagBean.navName);
                    mIntent.putExtra(BaseFragment.IS_SHOW_TOP, false);

//                    if (TextUtils.isEmpty(tagBean.navTitle)) {
//                        mIntent.putExtra(BaseFragment.IS_SHOW_TOP, false);
//                    } else {
//                        mIntent.putExtra(Constants.TITITL, tagBean.navName);
//                    }
                } else {
                    mIntent.putExtra(BaseFragment.IS_SHOW_TOP, true);
                }
//                if (BuildConfig.MODULE_KEY_WORKBENCH.equals(tagBean.navKey) && BuildCache.getAppConfigBean
// (mContext).navigationBean.navStyle == BuildConfig.NavStyle.DRAWER_STYLE.getType()) {
//                    mIntent.putExtra(MyWorkIndexFragment.i, true);
//                }
                mContext.startActivity(mIntent);
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String startNewModuleByKeyH5(String navKey, Context mContext) {
        try {
            if (BuildConfig.nativeMap.containsKey(navKey)) {
                BuildConfig.NativeSkip style = BuildConfig.nativeMap.get(navKey);
                Class clz = ClassUtil.getClassByName(style.getActivityClz());
                if (clz == null) {
                    return "";
                }
                return style.getActivityClz();
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


//    public static void setBeginButtonStyle(Context mContext, TextView textView) {
//        String backgroundColor = BuildCache.getAppConfigBean(mContext).guidePageBean.buttonBean.backgroundColor;
//        String borderColor1 = BuildCache.getAppConfigBean(mContext).guidePageBean.buttonBean.borderColor;
//        String textColor1 = BuildCache.getAppConfigBean(mContext).guidePageBean.buttonBean.textColor;
//        int backColor = Color.parseColor(backgroundColor);
//        int borderColor = Color.parseColor(borderColor1);
//        int textColor = Color.parseColor(textColor1);
//        textView.setText(BuildCache.getAppConfigBean(mContext).guidePageBean.buttonBean.showText);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//            textView.setBackground(DrawableUtils.getDrawable(mContext, backColor, borderColor, 10.0f,
//                    GradientDrawable.RECTANGLE));
//        }
//        textView.setText(BuildCache.getAppConfigBean(mContext).guidePageBean.buttonBean.showText);
//        textView.setTextColor(textColor);
//    }

    /**
     * 跳转到编辑页面
     *
     * @param mContext
     * @param dataBundle
     */
    public static void startInfoEditActivity(Context mContext, Bundle dataBundle) {
        Intent mIntent = new Intent(mContext, InfoEditActivity.class);
        mIntent.putExtra(KEY_BUNDLER, dataBundle);
        mContext.startActivity(mIntent);
    }

    public static void startApplyForm(Context mContext, String formUrl) {
        Intent in = new Intent(mContext, ClassUtil.getClassByName(ClassUtil.DCLOUD_WEBVIEW));
        String loadUrl;
        loadUrl = WorkLogConstant.getMyJyUrl(formUrl);
        LogUtil.i(Constants.WEBVIEURL, loadUrl);
        in.putExtra(Constants.WEBVIEURL, loadUrl);
        mContext.startActivity(in);
    }

    /**
     * 传递拼接好的url
     *
     * @param mContext
     * @param formUrl
     */
    public static void viewApplyFormDetail(Context mContext, String formUrl) {
        Intent in = new Intent(mContext, ClassUtil.getClassByName(ClassUtil.DCLOUD_WEBVIEW));
        in.putExtra(Constants.WEBVIEURL, formUrl);
        mContext.startActivity(in);
    }
}
